<template>

<div class="top">
    <div class="content">
        <!-- logo -->

        <div class="top_icon">
           <router-link to="/Home">
           <img src="../../src/assets/images/logo.png" alt="">
          </router-link>

        </div>
        <div class="top_info">
            <ul >
               <li
               v-for ="(item,index) in tab"
               @click="changeClass(index)"
               :class="{red: classActives == index}"
               :key= index
               >
                 <router-link :to="item.to">{{item.name}}</router-link>
               </li>
            </ul>
        </div>
        <div class="search">
            <span class="redHot"></span>

            <input type="text" placeholder="校车表"  v-model.trim="search" ref="SearchInput">
            <!-- 回车搜索功能 ：只有在焦点状态下才能发起搜索-->
            <button @click="Search" ref="searchBtn">
                <img src="../assets/images/搜索.png">
                <span >搜索</span>
            </button>
        </div>
        <div class="user" >
          <!-- 如果登录，则显示 -->
            <div class="userCenter" v-if="isLogin()">
                 <div class="avator">
                   <!-- 如果有头像，则显示用户设置头像 反之为默认头像 -->
                <img  v-if="havaAvator()"  :src="userInfo.photo">
                <img  v-else src="../../public/images/toux.jpg">

            </div>
                <li @click="$router.push('/user')"><p>{{userInfo.username}}</p></li>
                <li @click="$router.push('/user/userSet')"><p>个人中心</p></li>

                <li @click="backLogin"><p>退出</p></li>
            </div>
            <div class="top_login" v-else>

             <button class="login" @click ="Login" >登录</button>
            <button class="register" @click="backregister">注册</button>
        </div>
        </div>

    </div>

</div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex'
import { getUserInfo } from '../API/User.js'
import { search } from '../API/search.js'
export default {
  name: 'headNav',
  data () {
    return {
      backLoginIsShow: true,
      userInfo: {},
      currentPath: this.$route.path,
      searchObj: {
        trades: [],
        schArts: [],
        questions: []
      },
      classActives: null,
      //   判断用户是否为初始化头像
      avator: false,
      search: '',
      activa_status: '校园公告',
      tab: [
        {
          name: '首页',
          to: '/'
        },
        {
          name: '校园公告',
          to: '/schArt'
        },
        {
          name: '二手商品',
          to: '/trade'
        },
        {
          name: '问答交流',
          to: '/question'
        }
      ]
    }
  },
  methods: {
    ...mapMutations(['clearToken', 'updataUserInfo']),
    ...mapActions(['initUserInfo']),
    changeClass (index) {
      this.classActives = index
    },
    // 退出登录
    backLogin () {
      this.clearToken()

      // this.$router.push({
      //   path: '/Home'
      // })
      this.$router.go(0)
    },
    Login () {
      // this.clearToken()
      this.$router.push({
        path: '/login'
      })
    },
    // 判断是否登录
    backregister () {
      this.$router.push({
        path: '/login',
        query: {
          login: 'register'
        }
      })
    },
    isLogin () {
      if (JSON.stringify(this.userInfo)) {
        //   不渲染
        if (this.userInfo.username === undefined) {
        // console.log(this.userInfo.username)
        // this.userInfo.username = this.$store.state.userInfo
          return false
        } else {
        // this.userInfo.username = this.$store.state.userInfo

          return true
        // this.$router.go(0)
        }
      } else {
        return false
      }
    },
    toggleRed () {

    },
    havaAvator () {
      // console.log(this.userInfo.username.)
      if (this.userInfo.photo !== null) {
        return true
      } else {
        return false
      }
    },
    // 搜索功能
    async Search () {
      if (this.search !== '') {
        const path = this.$route.path
        if (path.indexOf('search') === -1) {
          this.$router.push({
            path: '/search',
            query: {
              keyword: this.search
            }
          })
        } else {
          this.$nextTick(async () => {
            const { data: res } = await search(this.search)
            this.searchObj.schArts = res.data[0].filter(item => {
              return item.isdelete === 0 && item.isdown === 0
            })
            this.searchObj.trades = res.data[1].filter(item => {
              return item.isdelete === 0 && item.isdown === 0
            })
            this.searchObj.questions = res.data[2].filter(item => {
              return item.isdelete === 0 && item.isdown === 0
            })
            this.$emit('searchDate', this.searchObj)
            this.$router.replace('/search?keyword=' + this.search)
          })
        }
      } else {
        this.$message({
          showClose: true,
          type: 'error',
          message: '搜索内容不能为空'
        })
      }
    },
    // 渲染用户数据
    // 当登录之后,如果有数据，先进行数据赋值，再实现页面渲染
    init () {
      this.$nextTick(async () => {
        const { data: res } = await getUserInfo()
        if (res.status === 0) {
          this.userInfo = res.data
        }
        // console.log(this.$store.state.userInfo)
      })

      // 将用户数据传入vuex中
      // this.updataUserInfo(res)
      // this.userInfo = res.data
    },
    // 当搜索框处于聚焦状态才能按回车进行搜索，否则不会搜索
    keydown (e) {
      const keyCode = e.keyCode
      if (keyCode === 13) {
        this.Search()
      }
    }
  },

  created () {
    // this.initUserInfo()
    this.initUserInfo()
    this.init()
    this.havaAvator()
    this.isLogin()
    // console.log(this.currentPath)
  },
  // mounted () {
  //   window.addEventListener('keydown', this.keydown)
  // },
  // deactivated () {
  //   window.removeEventListener('keydown', this.keydown, false)
  // },
  watch: {
    userInfo: {
      // const { data: res } = await getUserInfo()
      // console.log(res)
      // this.userInfo = new
      handler (newVal) {
        // this.userInfo = newVal

      },
      deep: true,
      immediate: true
    }

  }

}
</script>

<style lang="less" scoped>
*{
    margin: 0;
    padding: 0;
}
li{
    list-style: none;
}
a{
    text-decoration: none;
}
.top{
    width: 100%;
    height:1.375rem;
    border-bottom: 1px solid #dcdcdc;
    background-color: #fff;
    .content{
    width: 95%;
    height: 100%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .top_icon{
        flex: 2;
        justify-content: flex-start;
        display: flex;
        img{
        width:4rem ;
        height: 1.275rem;
    }

    }
    .top_info{
        flex: 6;
        ul{
            display: flex;
            align-items: center;
            li a{
                padding: .1667rem;
                margin: 0 .0833rem;
                font-size: .3rem;
                cursor: pointer;
                color: #000;
            }
            li a:hover{
            color:#fd8b8b;
             font-weight: 600;

            }
            .red a{
                font-weight: 600;
                color: #ff3535 !important;
            }

        }
    }
    .search{
        flex: 4;
        position: relative;
        display: flex;
        align-items: center;
        .redHot{
            position: absolute;
            width: .2667rem;
            height: .2667rem;
            background: url('../assets/images/精灵图1.png') no-repeat;
            background-position: -32px 0;
            left: .25rem;
            background-size: 300%;
        }
        input{
            font-size: 14px;
            display: inline-block;
            width: 3.3333rem;
            height: 100%;
            padding: 7px 0;
            line-height: inherit;
            border: 0 none;
            outline: 0;
            background: #f5f6f7;
            color: #222226;
            vertical-align: top;
            text-indent: 32px;
            border: 1px solid #e8e8ed;
            border-right: none;
            box-sizing: border-box;
            border-radius: 16px 0 0 16px;
            }
    button{
            display: inline-block;
            width: 70px;
            height: 100%;
            outline: 0;
            border: 0 none;
            border-radius: 0 15px 16px 0;
            font-size: 14px;
            line-height: 32px;
            cursor: pointer;
            -webkit-transition: all .2s ease-in;
            transition: all .2s ease-in;
            background-color: #0092EE;
            text-align: left;
            img{
                display: inline-block;
                width: 20px;
                height: 20px;
                background-position: 10px;
                background-size: 100%;
                vertical-align: middle;
                position: relative;
                padding: 0 3px;

            }
            span{
                display: inline-block;
                vertical-align: top;
                color: #fff;
            }
            }
            button:hover{
                background-color: #0087FF;
            }

        }

    }
    .top_login{
        flex: 7;
        display: flex;
        justify-content: flex-end;
        .login{
            padding: .1667rem .4167rem;
            border: 0;
            background-color: #409EFF;
            border-radius: .3333rem;
            color: #fff;
            margin: 0 .3333rem;
            cursor: pointer;

        }
        .login:hover{
            background-color: #0092EE;
        }
        .register{
            padding: .1667rem .4167rem;
            border: .0167rem solid #999;
            background-color: #FFF;
            border-radius: .3333rem;
            color: #000;
            margin: 0 .1667rem;
            cursor: pointer;
        }
        .register:hover{

            color: #fff;
            background-color: #409EFF;
        }
    }

    // 用户信息
    .user{
        display: flex;
        flex: 5;
        justify-content: center;
        align-items: center;
        padding-left: 0.5rem;
        .avator{
            width: 1rem;
            height: 1rem;

            // border-radius: 50%;
            img{
                width: 100%;
                height: 100%;
                cursor: pointer;
                border-radius: 50%;
            }
        }
        li:hover{
            color:#0092EE
        }
        .userCenter{
            display: flex;
            align-items: center;
           li {
                cursor: pointer;
                margin-left: .3333rem;
                font-size: .2667rem
            }
        }
    }

}

</style>>
